import { AudioClip } from "cc";
import { Handler } from "../event/Handler";
import { ResourceMgr } from "../ResourceMgr";


export class AudioData
{
    private effectlim:number = 5;

    private curbgmname:string = "";

    private effectAudioMap : Map<string,AudioInfo> = new Map<string,AudioInfo>();

    loadBgmAudio(filename:string,callback:Handler)
    {
        ResourceMgr.instance.LoadAudioClip(filename,callback);
        this.curbgmname = filename;
    }

    loadEffectAudio(filename:string,callback:Handler)
    {
        if(this.effectAudioMap.has(filename))
        {
            return this.effectAudioMap.get(filename);
        }
        else
        {
            if(this.effectAudioMap.size >= this.effectlim)
            {
                let keylist = Array.from(this.effectAudioMap.keys());
                for(let i = 0; i< keylist.length; ++i)
                {
                    let name = keylist[i];
                    let id = this.effectAudioMap.get(name).id;
                    let state = cc.audioEngine.getState(id);
                    if(state != cc.audioEngine.AudioState.PLAYING && state != cc.audioEngine.AudioState.INITIALZING)
                    {
                        this.effectAudioMap.delete(name);
                        ResourceMgr.instance.RealseAudioClip(name);
                    }
                }
            }
            ResourceMgr.instance.LoadAudioClip(filename,callback);
        }
        return null;
    }

    realseBgmRes()
    {
        if(this.curbgmname != "")
            ResourceMgr.instance.RealseAudioClip(this.curbgmname);
    }

    // 释放特效音效
    realseEffectRes()
    {
        let keylist = Array.from(this.effectAudioMap.keys());
        for(let i = 0; i < keylist.length;++i)
        {
            let name = keylist[i];
            this.effectAudioMap.delete(name);
            ResourceMgr.instance.RealseAudioClip(name);
        }
    }

    seteffectMap(key:string,id:number, clip:AudioClip)
    {
        let clipInfo = new AudioInfo(id,clip);
        this.effectAudioMap.set(key,clipInfo);
    }
}

class AudioInfo
{
    id : number;  // 音频Id
    audio : AudioClip;

    constructor(id,audio)
    {
        this.id = id;
        this.audio = audio;
    }
}